<template>
	<div class="zh-common-problem">
		<nav-header></nav-header>
		<div class="zh-tabs">
			<div class="zh-open-right fr" style="position: relative;z-index: 99;">
				<el-button type="primary" @click="addProblem()">添加问题</el-button>
				<el-button type="primary" @click="editProblemWord">分类管理</el-button>
				<el-button type="danger" @click="deleteMuiltProblem_confirm">批量删除</el-button>
			</div>

			<template v-if="problemTypeData.length > 0">
                <el-tabs v-model="activeName" type="card" @tab-click="changeTab">
                    <template v-for="(item, inx) in problemTypeData">
                        <el-tab-pane :label="item.name" :name="'tab-'+inx" :key="inx">
                            <div class="zh-table">
                                <div class="zh-table-open clear">
                                    <div class="zh-open-left fl">
                                        <el-button @click="orderChange" plain style="min-width: 80px;padding: 8px 15px;margin-right: 8px" v-text="sort[inx].status ? '排序' : '完成'"></el-button>
                                        <div class="open-width">
                                            <el-input v-model="keyword" placeholder="请输入标题搜索" @keyup.enter.native="searchFunc"></el-input>
                                        </div>
                                        <el-button type="primary" @click="searchFunc">搜索</el-button>
                                        <el-button type="primary" @click="reset">重置</el-button>
                                    </div>
                                    
                                </div>
                                <div class="zh-table-contents"
                                    v-loading="loading.status"
                                    :element-loading-text="loading.txt">
                                    <el-table :key="Math.random()"
                                        :data="item.data"
                                        @selection-change="tableSelectionChange"
                                        border
                                        :ref="'form' + inx"
                                        max-height="600"
                                        style="width: 100%">
                                        <el-table-column
                                        type="selection"
                                        width="50"
                                        align="center"
                                        fixed>
                                        </el-table-column>
                                        <el-table-column
                                        prop="order_num"
                                        label="序号"
                                        align="center"
                                        width="80"
                                        show-overflow-tooltip
                                        >
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.order_num" :disabled="sort[inx].status"></el-input>
                                        </template>
                                        </el-table-column>
                                        <el-table-column
                                        prop="title"
                                        label="标题"
                                        align="center"
                                        show-overflow-tooltip
                                        >
                                        </el-table-column>
                                        <!-- <el-table-column
                                        prop="clicks"
                                        label="点击量"
                                        align="center"
                                        show-overflow-tooltip
                                        >
                                        </el-table-column> -->
                                        <el-table-column
                                        prop="create_name"
                                        label="发布人"
                                        align="center"
                                        show-overflow-tooltip
                                        >
                                        </el-table-column>
                                        <el-table-column
                                        prop="create_time"
                                        label="更新时间"
                                        align="center"
                                        show-overflow-tooltip
                                        >
                                        </el-table-column>
                                        <el-table-column
                                        label="操作"
                                        align="center"
                                        show-overflow-tooltip
                                        >
                                            <template slot-scope="scope">
                                                <el-button @click="changeProblem_confirm(scope.row,2)" v-if="parseInt(scope.row.status) === 1" type="text" >隐藏</el-button>
                                                <el-button @click="changeProblem_confirm(scope.row,1)" v-if="parseInt(scope.row.status) === 2" type="text" >显示</el-button>
                                                <el-button @click="editProblem(scope.row.id)" type="text">编辑</el-button>
                                                <el-button @click="deleteProblem_confirm(scope.row)" type="text" class="delete-button">删除</el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    <div class="table-pagination" v-show="total_number > 10">
                                        <el-pagination
                                            @size-change="handleSizeChange"
                                            @current-change="handleCurrentChange"
                                            :current-page="problemParam.page_index"
                                            :page-sizes="[10, 20, 30, 40, 50, 100]"
                                            :page-size="problemParam.page_size"
                                            layout="total, sizes, prev, pager, next, jumper"
                                            :total="total_number">
                                        </el-pagination>
                                        <div class="pagination-button">
                                            <el-button 
                                                @click="getList"
                                                type="primary" icon="el-icon-refresh" 
                                                circle title="刷新数据" size="mini" >
                                            </el-button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-tab-pane>
                </template>
                </el-tabs>
            </template>

            <div v-else class="zh-table-contents" style="padding-top: 50px;">
                <el-table
                    :data="problemTypeData"
                    border
                    max-height="600"
                    style="width: 100%">
                    <el-table-column
                        type="selection"
                        width="50"
                        align="center"
                        fixed>
                    </el-table-column>
                    <el-table-column
                        prop="order_num"
                        label="序号"
                        align="center"
                        width="80"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="title"
                        label="标题"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="clicks"
                        label="点击量"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="create_name"
                        label="发布人"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="create_time"
                        label="更新时间"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                </el-table>
            </div>
		</div>

		<!-- 编辑问题 -->
		<el-dialog 
            :close-on-click-modal="false" 
            :close-on-press-escape="false" 
            :before-close="cancelEdit" 
            title="编辑分类" 
            :visible.sync="EditproblemWords" 
            class="editproblem" 
            width="500px">
			<el-form :model="editForm" ref="editForm" :rules="rules" status-icon label-position="left" label-width="100px">
			    <el-form-item label="分类名称" class="fromWidth" prop="temp_type_name">
			      	<el-input 
			      		v-model="editForm.temp_type_name" 
			      		placeholder="请输入分类名称（10个字符）" 
			      		autocomplete="off" 
			      		:maxlength="parseInt(10)"
			      		clearable>
			      	</el-input>
			      	<el-button type="primary" @click="addproblemtype">添加</el-button>
			    </el-form-item>
			    <el-form-item label="问题分类">
			      	<el-tag
			      	  :key="inx"
			      	  v-for="(item,inx) in problemtypeTag"
			      	  closable
			      	  :disable-transitions="false"
			      	  @close="delproblemtype(inx)">
			      	  {{item.name}}
			      	</el-tag>
			    </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cancelEdit">取消</el-button>
			    <el-button type="primary" @click="saveproblemtype">保存</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
  	export default {
	    data() {
	      	return {
	      		loading:{
					status:false,
					txt:'获取数据...',
				},
                sort: [],
	      		problemTypeData:[],
	        	activeName: 'tab-0',
	        	activeIndex:0,
	        	problemParam:{
	        		keyword:'',
	        		type_id:0,
					page_index:1,
					page_size:10,
				},
				keyword: '',
	        	total_number:0,
	        	selected:[],
	        	status_arr:{1:'显示',2:'隐藏'},

	        	problemtypeTag:[],
	        	EditproblemWords: false,
                editForm: {
                  	temp_type_name: '',
                },
                rules: {
                	temp_type_name :[
						{ required: true, message: '请输入名称', trigger: 'blur' },
						{ min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
					],
                },
				rowLen: 0,
	      	};
	    },
	    created(){
			this.getProblemType();
	    },
	    methods: {
            /**
             * 编辑分类管理
             */
            editProblemWord() {
                this.EditproblemWords = true;
                this.problemtypeTag = deep_clone(this.problemTypeData);
            },
			cancelEdit() {
				this.$refs.editForm.clearValidate();
				this.EditproblemWords = false;
				this.editForm.temp_type_name = '';
			},
	    	searchFunc(){
				this.problemParam.page_index = 1;
				this.problemParam.keyword = this.keyword;
				this.getList();
			},
			reset() {
				this.problemParam.page_index = 1;
				this.keyword = '';
				this.problemParam.keyword = '';
				this.problemParam.page_size = 10;
				this.getList();
			},
			orderChange(){
				
				if(this.sort[this.activeIndex].status) {
					this.sort[this.activeIndex].status = false;
				} else {
					let success = ( data => {
						this.sort[this.activeIndex].status = true;
						this.loading.status = false;
						this.$message.success( data.msg) ;
						this.getList();
					});
					let params = {
						id:getOneColumn( this.problemTypeData[this.activeIndex].data , 'id' ),
						order_num: getOneColumn( this.problemTypeData[this.activeIndex].data , 'order_num')
					}
					this.$ajax.post('api/setting/problem_order',params,{func:{success:success}})
				}
			},
	    	addproblemtype(){
		    	this.$refs['editForm'].validate((valid) => {
					if (valid) {
						if( this.problemtypeTag.length >= 10) {
				    		return this.$message.warning('分类添加超过最大限制数10个');
				    	}
				    	for (var i = this.problemtypeTag.length - 1; i >= 0; i--) {
				    		if( this.problemtypeTag[i].name == this.editForm.temp_type_name ){
				    			return this.$message.warning('分类名称不能重复添加');
				    		}
				    	}
				    	this.problemtypeTag.push({i_s:0,name:this.editForm.temp_type_name,id:0});
				    	this.$refs.editForm.resetFields()// 清除表单验证
					} else {
						return false;
					}
				});
		    },
		    delproblemtype(tag) {
                if (this.problemtypeTag[tag].i_s === 0) {
                    this.problemtypeTag.splice(tag, 1);
                } else {
                    let success = (res => {
                        if(res.data.result) {
                            this.$message.warning('该分类下存在常见问题，不能删除');
                            return false;
                        }else{
                            this.problemtypeTag.splice(tag, 1);
                        }
                    });

                    this.$ajax.get('/api/setting/existproblem_by_type',{params:{id:this.problemtypeTag[tag].id},func:{success:success}})
                }
	        },
	        saveproblemtype(){
	        	// 重写成功回调
				let success = ( data => {
                    this.$message.success(data.msg);
                    
                    this.$refs.editForm.clearValidate();
                    this.EditproblemWords = false;
                    this.editForm.temp_type_name = '';
                
					this.getProblemType();
				});
  				this.$ajax.post('/api/setting/problem_type',this.problemtypeTag,{func:{success:success}})
	        },
	    	 getProblemType(){
	    	 	this.loading.status = true;
		    	
				let success = ( data => {
					this.problemtypeTag = deep_clone( data.data );
					this.loading.status = false;
                    this.problemTypeData = data.data;
                    
					if( this.problemTypeData.length > 0 ){
						for (var i = this.problemTypeData.length - 1; i >= 0; i--) {
							this.problemTypeData[i].data = [];
							this.sort.push({status: true});
						}
						this.problemParam.type_id = this.problemTypeData[0].id;
						this.getList();
					}
					
				});
				let fail = ( data => {
					this.loading.status = false;
					this.$message.error(data.msg)
					
				})
  				this.$ajax.get('api/setting/problem_type',{params:{},func:{success:success,fail:fail}})
		    	
		    },
		    getList(){
		    	this.loading.status = true;
				// 重写成功回调
				let success = ( data => {
					this.loading.status = false;
					this.problemTypeData[this.activeIndex].data = data.data.data;
					this.total_number = data.data.data_sum;
					this.$forceUpdate();//强制渲染
				});
				let fail = (data => {
					this.loading.status = false;
					this.$message.error(data.msg);
				})
	
  				this.$ajax.get('api/setting/problem_data',{params:this.problemParam,func:{success:success,fail:fail}})
		    },
	    	//添加问题
			addProblem(){
				this.$router.push("/portal/help/add-question")
			},
			//添加问题
			editProblem(id){
				this.$router.push("/portal/help/add-question/"+id)
			},
			
			//选中
		    tableSelectionChange(val) {
                this.selected = val;
            },
			deleteClick(row){
				
			},
		    handleSizeChange(val) {
		    	this.problemParam.page_index = 1;
		    	this.problemParam.page_size = val;
		    	this.getList();
		    },
		    handleCurrentChange(val) {
		    	this.problemParam.page_index = val;
		    	this.getList();
		    },
	      	changeTab(tab, event) {
	      		var inx = parseInt(tab.index );
	      		if( inx !== this.activeIndex ){
	      			this.activeIndex = inx;
					this.problemParam.type_id = this.problemTypeData[inx].id;
					this.problemParam.page_index = 1;
					this.problemParam.keyword = '';
					this.keyword = '';
	      			this.getList();
	      		}
	      		
	      	},
	      	deleteProblem_confirm(obj){
				let yes = ( data => {
					this.changeProblem(obj.id,0);
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.title+' 删除吗？'});

			},
	      	 changeProblem_confirm(obj,status){
				let yes = ( data => {
					this.rowLen = 1;
					this.changeProblem(obj.id,status);
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.title+' 标记为 '+this.status_arr[parseInt(status)]+' 吗？'});

			},
		    
	      	deleteMuiltProblem_confirm(){
				if( this.selected.length === 0 ) {
					this.$message.warning("请选择要删除的项");
					return false;
				}
				let yes = ( data => {
					this.rowLen = this.selected.length;
					this.deleteMuiltProblem();
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定要删除选中的项吗？'});

			},
	      	deleteMuiltProblem(){
				var ids = [];
				for (var i = this.selected.length - 1; i >= 0; i--) {
					ids.push(this.selected[i].id)
				}
				this.changeProblem(ids,0);
			},
			
		    changeProblem(id, status){
		    	let success = ( data => {
					this.$message.success(data.msg);

					if (this.problemTypeData[this.activeIndex].data.length - this.rowLen === 0) {
						if (this.problemParam.page_index > 1) {
							this.problemParam.page_index--;
						} else {
							this.problemParam.page_index = 1;
						}
					}				

					this.getList();
				});
		    	this.$ajax.put('api/setting/change_problem',{id:id,status:status},{func:{success:success}})
		    },
	    }
  	};
</script>
<style lang="scss">
	.zh-common-problem {
		.el-table__body-wrapper table tbody {
			td:nth-child(7) {
				padding: 0;
			}
		}
		.zh-tabs {
			margin-top: 15px;
		}
		.editproblem {
			.fromWidth {
				.el-input {
					width: 220px;
				}
				.el-button {
					min-width: 80px;
					margin-left: 8px;
				}
			}
			.el-tag {
			    margin-right: 10px;
			}
		}
	}
</style>